/*
 * Created on 29.08.2007
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package at.fhv.dcs.aw.j2me.lcdui.lowlevel.sort;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class DoubleBufferingClippingRegionSortingCanvas extends SortingCanvas {
    private Image m_buffer;
    private Graphics m_graphics;
    
    public DoubleBufferingClippingRegionSortingCanvas() {
        m_buffer = Image.createImage(getWidth(), getHeight());
        m_graphics = m_buffer.getGraphics();
        
    }
    protected void paint(Graphics g) {
        int mid = m_buffer.getWidth() / 2;
        
        int x = g.getClipX();
        int y = g.getClipY();
        int w = g.getClipWidth();
        int h = g.getClipHeight();
        
        synchronized (m_values) {
            for (int i = y ; i < (y + h) ; i++) {
                m_graphics.setColor(WHITE);
                m_graphics.drawLine(x, i , x + w - 1, i);
                
                m_graphics.setColor(BLACK);
                m_graphics.drawLine(mid - m_values[i], i , mid + m_values[i], i);
            }
        }
        
        g.drawImage(m_buffer, 0, 0, Graphics.TOP | Graphics.LEFT);
    }
    
    public void run() {
       //implement bubble sort
            for (int i = m_values.length - 1; i >= 0; i--) {
                for (int j = 0; j < i; j++) {
                    synchronized (m_values) {
                        if (m_values[j] > m_values[j + 1]) {
                            int tmp = m_values[j];
                            m_values[j] = m_values[j + 1];
                            m_values[j + 1] = tmp;
                            
                            repaint(0, j , getWidth(), 2);
                        }
                        
                    }
                }
            }
            
            if (m_thread != Thread.currentThread())  { //check for end
                return;
            }
    }
}